package com.geek.novel.services

import android.content.res.Resources
import com.geek.novel.bo.AppContext
import com.geek.novel.entity.BookIndex
import com.geek.novel.utils.GsonUtil
import com.vicpin.krealmextensions.delete
import com.vicpin.krealmextensions.query
import com.vicpin.krealmextensions.save
import io.realm.Realm

class BookIndexRepository{
	
	private fun getResources(): Resources {
		return AppContext.getResources()
	}
	
	/**保存*/
	fun save(bookIndex: BookIndex){
		bookIndex.save()
	}
	
	/**保存List*/
	fun saveAll(list: List<BookIndex>){
		val jsonList = GsonUtil.toJson(list)
		val realm = Realm.getDefaultInstance()
		//开启事务，然后批量保存
		realm.executeTransaction {
			it.createOrUpdateAllFromJson(BookIndex::class.java, jsonList)
		}
	}

	/**根据bookId获取数据，只在本地书籍上使用*/
	fun findByBookId(bookId: String): List<BookIndex> {
		return BookIndex().query { equalTo("bookId", bookId) }
	}
	
	/**根据bookId和bookCrawlerId获取数据*/
	fun findByBookIdAndBookCrawlerId(bookId: String, bookCrawlerId: String): List<BookIndex> {
		return BookIndex().query { equalTo("bookId", bookId).and().equalTo("bookCrawlerId", bookCrawlerId) }
	}

	/**
	 * 删除已经爬取过的章节
	 */
	fun deleteByBookId(bookId: String){
		BookIndex().delete { equalTo("bookId", bookId) }
	}

}